var express = require('express');
var router = express.Router();
var models = require('../models');
const {success, error} = require('../utils/messages')

// 查出所有数据
router.get('/', async function (req, res, next) {
    const profession = await models.Profession.findAll({order: [['id', 'DESC']]})
    success(res, '查询成功', {profession})
});

// 查出所有行业名称数据
router.get('/name', async function (req, res, next) {
    const profession = await models.Profession.findAll()
    const professionName=[]
    for(let i=0;i<profession.length;i++){
        professionName.push(profession[i].name)
    }
    success(res, '查询成功', {professionName})
});
// 查出所有行业人数数据
router.get('/num', async function (req, res, next) {
    const profession = await models.Profession.findAll()
    const professionNum=[]
    for(let i=0;i<profession.length;i++){
        professionNum.push(profession[i].num)
    }
    success(res, '查询成功', {professionNum})
});

// 新增行业
router.post('/', async function (req, res, next) {
    //res.json(req.body)
    if (!req.body.name) {
        return error(res, '请填写行业名称')
    }

    if (!Number(req.body.num)) {
        return error(res, '数量必须是数字')
    }

    const profession = await models.Profession.create(req.body)
    success(res, '新增成功', {profession})
});

//查询行业
router.get('/:id', async function (req, res, next) {
    const profession = await models.Profession.findByPk(req.params.id)
    success(res, '查询成功', {profession})
});
// 编辑行业
router.put('/:id', async function (req, res, next) {
    const profession = await models.Profession.findByPk(req.params.id)
    if (!req.body.name) {
        return error(res, '请填写行业名称')
    }
    if (!req.body.num) {
        return error(res, '请填写行业人数')
    }

    profession.update(req.body);
    success(res, '编辑成功', {profession})
});

// 删除行业
router.delete('/:id', async function (req, res, next) {
    const profession = await models.Profession.findByPk(req.params.id)
    profession.destroy();
    success(res, '删除成功！')
});


module.exports = router;
